package com.sign2024.sign2024core.common.aspect;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yujie
 * @data 2024/8/6 10:26
 */
@Slf4j
@Aspect
@Component
public class LogAspectInfo {

    // 针对指定的注解设置切点
//    @Pointcut("@annotation(com.sign2024.sign2024core.common.annotation.LogInfo)")
    @Pointcut("@annotation(com.sign2024.sign2024core.common.annotation.Log)")
    public void pointcut() {
    }

//    @Before("pointcut()")
//    public void before(JoinPoint joinPoint) {
//        // 获取方法名
//        String name = joinPoint.getSignature().getName();
//        // 获取方法的参数
//        Object[] args = joinPoint.getArgs();
//
//        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
//        Method method = signature.getMethod();
//
//        // 获取方法的请求路径
//        HttpServletRequest request =
//                ((ServletRequestAttributes) RequestContextHolder
//                        .getRequestAttributes()).getRequest();
//        // 请求路径
//        String url = request.getRequestURI();
//
//        // 获取方法的参数信息
//        Parameter[] parameters = method.getParameters();
//
//        Map<String, Object> map = new HashMap<>();
//        if (args != null) {
//            for (int i = 0; i < parameters.length; i++) {
//                map.put(parameters[i].getName(), args[i]);
//            }
//        }
//
//        ObjectMapper objectMapper = new ObjectMapper();
//        try {
//            String paramJson = objectMapper.writeValueAsString(map);
//            // 将参数去掉
//            log.info("method:{}, params:{}, url:{}", name, paramJson, url);
//            log.info("method:{}, url:{}", name, url);
////        } catch (JsonProcessingException e) {
//        } catch (Exception e) {
//            log.error("Error serializing parameters to JSON", e);
//        }
//    }

    @Before("pointcut()")
    public void before(JoinPoint joinPoint) {
        // 获取方法名
        String name = joinPoint.getSignature().getName();
        // 获取方法的参数
        Object[] args = joinPoint.getArgs();

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        // 获取方法的请求路径
        HttpServletRequest request =
                ((ServletRequestAttributes) RequestContextHolder
                        .getRequestAttributes()).getRequest();
        // 请求路径
        String url = request.getRequestURI();

        // 获取方法的参数信息
        Parameter[] parameters = method.getParameters();

        Map<String, Object> map = new HashMap<>();
        if (args != null) {
            for (int i = 0; i < parameters.length; i++) {
                Object arg = args[i];
                if (arg != null && isSerializable(arg)) {
                    map.put(parameters[i].getName(), arg);
                } else {
                    map.put(parameters[i].getName(), "unserializable");
                }
            }
        }

        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String paramJson = objectMapper.writeValueAsString(map);
            log.info("method:{}, params:{}, url:{}", name, paramJson, url);
        } catch (JsonProcessingException e) {
            log.error("Error serializing parameters to JSON", e);
        }
    }

    @AfterThrowing(pointcut = "pointcut()", throwing = "ex")
    public void afterThrowing(JoinPoint joinPoint, Throwable ex) {
        // 获取方法名
        String name = joinPoint.getSignature().getName();

        // 获取方法的请求路径
        HttpServletRequest request =
                ((ServletRequestAttributes) RequestContextHolder
                        .getRequestAttributes()).getRequest();
        // 请求路径
        String url = request.getRequestURI();

        // 获取异常信息
        String errorMessage = ex.getMessage();

        // 记录错误日志
        log.error("Exception occurred in method: {}, url: {}, exception: {}", name, url, errorMessage, ex);
    }

    // 过滤无法被反序列化部分
    private boolean isSerializable(Object obj) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.writeValueAsString(obj);
            return true;
        } catch (JsonProcessingException e) {
            return false;
        }
    }
}
